package bank;

import java.util.ArrayList;
import java.util.List;

public class CardDaoImpl implements CardDao{

	// 初始化就读取文件
	List<Card> cardList = FileUtils.readFile();
	
	@Override
	public boolean insert(Card card) {
		if (cardList.contains(card)) {
			return false;
		}else {
			return cardList.add(card) && FileUtils.writeToFile(cardList);
		}
	}

	@Override
	public boolean deleteById(int cardId) {
		// 遍历集合中的卡
		for(Card card : cardList) {
			// 找到要删除的卡号 并且删除状态是false   boolean变量==false -> !boolean变量
			if (card.getCardId() == cardId && !card.isDeleteFlag()) {
				card.setDeleteFlag(true);
				FileUtils.writeToFile(cardList);
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean addMoney(int cardId, double money) {
		for (Card card : cardList) {
			if (card.getCardId() == cardId && !card.isDeleteFlag()) {
				card.setMoney(card.getMoney() + money);
				FileUtils.writeToFile(cardList);
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean takeMoney(int cardId, double money) {
		for (Card card : cardList) {
			// 卡号的对，删除状态也对，钱得够
			if (card.getCardId() == cardId && !card.isDeleteFlag() && card.getMoney() >= money) {
				card.setMoney(card.getMoney() - money);
				FileUtils.writeToFile(cardList);
				return true;
			}
		}
		return false;
	}

	@Override
	public double selectMoney(int cardId) {
		for (Card card : cardList) {
			// 卡号的对，删除状态也对，钱得够
			if (card.getCardId() == cardId && !card.isDeleteFlag()) {
				return card.getMoney();
			}
		}
		return -1;
	}
}
